package com.gxuwz.endrskyweather.apiclient;

import android.util.Log;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gxuwz.endrskyweather.model.*;
import com.gxuwz.endrskyweather.sampledata.Weather15d;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class ApiClient implements IApiClient {
    public static final String BASE_URL = "https://m1.apifoxmock.com/m1/6556374-6260553-default/lundear/weather1d";
    public static final String API_KEY = "YOUR_API_KEY_HERE";

    private OkHttpClient client;
    private Gson gson;

    private String jsonString;

    // 无缓存构建，将直接访问API并消耗点数
    public ApiClient() {
        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
        gson = new Gson();
        jsonString = null;
        Log.w("ApiClient", "ApiClient:" + "警告：使用了一次无缓存构建");
    }

    // 有缓存构建，将直接使用缓存数据
    public ApiClient(String jsonString) {
        this.jsonString = jsonString;
        client = null;
        gson = new Gson();
    }

    // 内部获取原始JSON字符串
    private String httpGet(String url) throws IOException {
        if (jsonString != null) return jsonString;
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            Log.w("ApiClient", "ApiClient:" + "警告：内部调用了一次API");
            return response.body().string();
        }
    }

    // 外部获取 json 字符串作为缓存
    public String httpGetJsonString(String cityCode) throws IOException {
        Request request = new Request.Builder()
                .url(BASE_URL)
                .build();
        try (Response response = client.newCall(request).execute()) {
            Log.w("ApiClient", "ApiClient:" + "警告：调用了一次API刷新了缓存");
            return response.body().string();
        }
    }

    public AlarmList getAlarmList(String cityCode) throws IOException, JSONException {
        Log.d("ApiClient", "获取到的CityCode:" + cityCode);
        String url = BASE_URL;
        String json = httpGet(url);
        JSONObject data = new JSONObject(json).getJSONObject("data").getJSONObject("alarmList");
        return gson.fromJson(data.toString(), AlarmList.class);
    }

    // 获取生活指数数据
    public LifeIndex getLifeIndex(String cityCode) throws IOException, JSONException {
        Log.d("ApiClient", "获取到的CityCode:" + cityCode);
        String url = BASE_URL;
        String json = httpGet(url);
        JSONObject data = new JSONObject(json).getJSONObject("data").getJSONObject("lifeIndex");
        return gson.fromJson(data.toString(), LifeIndex.class);
    }

    // 获取当前天气数据
    public Now getNowWeather(String cityCode) throws IOException, JSONException {
        Log.d("ApiClient", "获取到的CityCode:" + cityCode);
        String url = BASE_URL;
        String json = httpGet(url);
        JSONObject data = new JSONObject(json).getJSONObject("data").getJSONObject("now");
        return gson.fromJson(data.toString(), Now.class);
    }

    // 获取白日天气数据
    public Day getDayWeather(String cityCode) throws IOException, JSONException {
        Log.d("ApiClient", "获取到的CityCode:" + cityCode);
        String url = BASE_URL;
        String json = httpGet(url);
        JSONObject data = new JSONObject(json).getJSONObject("data").getJSONObject("day");
        return gson.fromJson(data.toString(), Day.class);
    }

    // 获取夜间天气数据
    public Night getNightWeather(String cityCode) throws IOException, JSONException {
        Log.d("ApiClient", "获取到的CityCode:" + cityCode);
        String url = BASE_URL;
        String json = httpGet(url);
        JSONObject data = new JSONObject(json).getJSONObject("data").getJSONObject("night");
        return gson.fromJson(data.toString(), Night.class);
    }

    // 获取逐小时天气预报数据
    public List<Hour1dataItem> getHour1Forecast(String cityCode) throws IOException, JSONException {
        Log.d("ApiClient", "获取到的CityCode:" + cityCode);
        String url = BASE_URL;
        String json = httpGet(url);
        JSONArray array = new JSONObject(json).getJSONObject("data").getJSONArray("hour1data");
        return gson.fromJson(array.toString(), new TypeToken<List<Hour1dataItem>>(){}.getType());
    }

    // 获取3小时预报数据
    public List<String> getHour3Forecast(String cityCode) throws IOException, JSONException {
        Log.d("ApiClient", "获取到的CityCode:" + cityCode);
        String url = BASE_URL;
        String json = httpGet(url);
        JSONArray array = new JSONObject(json).getJSONObject("data").getJSONArray("hour3data");
        return gson.fromJson(array.toString(), new TypeToken<List<String>>(){}.getType());
    }

    // 获取7天预报数据: 模拟数据
    public Map<String, ForecastDay> get7DayForecast(String cityCode) throws IOException, JSONException {
    //        String url = BASE_URL;
//        String json = httpGet(url);
        Log.d("ApiClient", "获取到的CityCode:" + cityCode);
        String json = Weather15d.getJson(); // 假设 Weather15d.getJson() 返回 JSON 字符串
        JSONObject jsonObject = new JSONObject(json).getJSONObject("data");
        Map<String, ForecastDay> forecastMap = new HashMap<>();
        Type forecastDayType = new TypeToken<ForecastDay>(){}.getType();
        // 遍历 JSON 对象中的每个预报日
        for (Iterator<String> it = jsonObject.keys(); it.hasNext(); ) {
            String dayKey = it.next();
            if (dayKey.startsWith("d")) {
                ForecastDay forecastDay = gson.fromJson(jsonObject.getJSONObject(dayKey).toString(), forecastDayType);
                forecastMap.put(dayKey, forecastDay);
            }
        }
        return forecastMap;
    }

    // 获取15天预报数据: 模拟数据
    public Map<String, ForecastDay> get15DayForecast(String cityCode) throws IOException, JSONException {
        Log.d("ApiClient", "获取到的CityCode:" + cityCode);
//        String url = BASE_URL;
//        String json = httpGet(url);
        Log.d("ApiClient", "获取到的CityCode:" + cityCode);
        String json = Weather15d.getJson(); // 假设 Weather15d.getJson() 返回 JSON 字符串
        JSONObject jsonObject = new JSONObject(json).getJSONObject("data");
        Map<String, ForecastDay> forecastMap = new HashMap<>();
        Type forecastDayType = new TypeToken<ForecastDay>(){}.getType();
        // 遍历 JSON 对象中的每个预报日
        for (Iterator<String> it = jsonObject.keys(); it.hasNext(); ) {
            String dayKey = it.next();
            if (dayKey.startsWith("d")) {
                ForecastDay forecastDay = gson.fromJson(jsonObject.getJSONObject(dayKey).toString(), forecastDayType);
                forecastMap.put(dayKey, forecastDay);
            }
        }
        return forecastMap;
    }

    // 获取24小时观测数据
    public Observe24h getObserve24h(String cityCode) throws IOException, JSONException {
        Log.d("ApiClient", "获取到的CityCode:" + cityCode);
        String url = BASE_URL;
        String json = httpGet(url);
        JSONObject data = new JSONObject(json).getJSONObject("data").getJSONObject("observe24h");
        return gson.fromJson(data.toString(), Observe24h.class);
    }


}
